﻿using System;
using System.Collections.Generic;
using System.Linq;
using ServiceHost.Model;

namespace ServiceHost
{
    public class DeviceCoordinatesHelper
    {
        public static Coordinate GetDeviceCoordinate(string token)
        {
            using (var ctx = new SafeRouteDataContext())
            {
                var res = GetByToken(token, ctx);

                if (res != null)
                {
                    return new Coordinate(res.X, res.Y);
                }

                return null;
            }
        }

        private static DeviceCoordinate GetByToken(string token, SafeRouteDataContext ctx)
        {
            return ctx.DeviceCoordinates.FirstOrDefault(p => p.Token == token);
        }

        public static void SetDeviceCoordinate(Coordinate coordinate, string token)
        {
            using (var ctx = new SafeRouteDataContext())
            {
                var res = GetByToken(token, ctx);

                if (res != null)
                {
                    res.X = coordinate.X;
                    res.Y = coordinate.Y;
                    res.Token = token;
                }
                else
                {
                    res = new DeviceCoordinate
                    {
                        X = coordinate.X,
                        Y = coordinate.Y,
                        Token = token
                    };

                    ctx.DeviceCoordinates.Add(res);
                }

                ctx.SaveChanges();
            }
        }

        public static List<string> GetNearByDeviceTokens(Coordinate coordinate)
        {
            using (var ctx = new SafeRouteDataContext())
            {
                var res = ctx.DeviceCoordinates
                    .Where(p => coordinate.Distance(new Coordinate(p.X, p.Y)) < Const.TownMinDistance)
                    .Select(p => p.Token);

                return res.ToList();
            }
        }
    }
}